using System.Reflection;

namespace CloudShot.ViewModels
{
  internal abstract class PropertyHandlerBase<T> 
  {
    protected PropertyInfo PropertyInfo { get; private set; }
    private T _initialValue;
    protected T CurrentPreviewValue;
    protected PropertiesFormViewModel ViewModel;

    protected T InitialValue
    {
      get { return _initialValue; }
      set
      {
        _initialValue = value;
        UpdateButtons(value);
        CurrentPreviewValue = value;
      }
    }

    protected PropertyHandlerBase(PropertyInfo propertyInfo)
    {
      PropertyInfo = propertyInfo;
    }

    protected abstract void UpdateButtons(T value);

    public virtual void SetViewModel(PropertiesFormViewModel viewModel)
    {
      if (viewModel != null)
      {
        InitialValue = (T)PropertyInfo.GetValue(viewModel);
      }
      else if (ViewModel!=null && !Equals(InitialValue, CurrentPreviewValue))
      {
        //NOTE: equals is required to optimize refresh count
        PropertyInfo.SetValue(ViewModel, InitialValue, null);
        InvokeRefreshRequest(ViewModel);
      }

      ViewModel = viewModel;
    }

    public void RefreshProperty()
    {
      InitialValue = (T)PropertyInfo.GetValue(ViewModel);
    }

    protected abstract void InvokeRefreshRequest(PropertiesFormViewModel viewModel);
  }
}